package jplat.api.rel.controller;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jplat.tools.coder.JsonCoder;
import jplat.tools.config.JSystemConfig;
import jplat.tools.string.StringUtil;
import jplat.tools.string.XLog;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import a.autocode.JBaseConfigInfo;

@Controller
public class JAPIReleaseController
{
	private static final String SERVICE_CODE="serviceCode";	//服务名称-用于映射对应分服务详情.
	private static final String REF_URL="refUrl";			//被引用的url.
	private static final String CHANGE="change";			//接口最新修改内容，最新修改即可.
	private static final String GTIME="gtime";				//接口最近时间.
	private static final String CH_NAME = "chName";			//chName
	
	//模块描述文件包.
	private String jsonPath = "jplat.api.rel";
	
	//接口描述文件包名.
	private String portPath = "a.autocode.app.port.backup";
	
	//接口描述文件资源路径.
	private String detailPath = portPath.replace(".", File.separator)+File.separator;
	
	//主机名称.
	private String hostUrl=JSystemConfig.getInstance().getString("app.url");
	
	
	/**
	 * API发布总入口.
	 * @author zhangcq
	 * @date Jan 13, 2017
	 * @comment rel = release.
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/api/all/rel.do")
	public String showAllAPIs( HttpServletRequest request, HttpServletResponse response )
	{
		return "";
	}

	/**
	 * 根据模块查询该模块的接口列表接口信息.
	 * @author zhangcq
	 * @date Jan 13, 2017
	 * @comment 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/api/{moduleName}/list.do")
	public String showThePortList( HttpServletRequest request,
									HttpServletResponse response,
										@PathVariable String moduleName )
	{
		String jsonStr = loadPackageFile(jsonPath,moduleName+"_md.json");
		if ( StringUtil.isEmpty(jsonStr) )
		{
			return "jsp/error";
		}
		
		XLog.log("jsonStr=%s", jsonStr);
		
		Map jsonMap = JsonCoder.fromJsonString(jsonStr, Map.class);
		XLog.log("jsonMap---%s---", JsonCoder.toJsonString(jsonMap));
		
		List<Map<String,String>> portList = (List<Map<String,String>>)jsonMap.get("services");
		
		Map<String,String> seviceItem = null;
		JBaseConfigInfo portConfig = null;
		JAPIParser apiParse = null;
		for ( int i = 0; i < portList.size(); ++i )
		{
			//获取服务详细信息.
			seviceItem = portList.get(i);
			String portDetailFile = "classpath:"+detailPath+seviceItem.get(SERVICE_CODE)+".port";
			XLog.log("portDetailFile=%s", portDetailFile);
			apiParse = new JAPIParser(portDetailFile);
			
			try {
				apiParse.doParse();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			portConfig = apiParse.config;
			
			seviceItem = portList.get(i);
			
			//优先使用这个url.因为model可以被多个url公用.
			if ( seviceItem.get(REF_URL) == null )
			{
				seviceItem.put(REF_URL, portConfig.getRefUrl());
			}
			
			//优先使用map中的接口描述，理由同上,bean:1-->url:n
			if ( seviceItem.get(CH_NAME) == null )
			{
				seviceItem.put(CH_NAME, portConfig.getBeanDesc());
			}
			
			//修改内容.
			seviceItem.put(CHANGE, portConfig.getChange() );
			
			//修改时间.
			seviceItem.put(GTIME, portConfig.getGdate());
		}

		request.setAttribute("hostUrl", hostUrl);
		request.setAttribute("moduleInfo", jsonMap);
		request.setAttribute("portList", portList);
		
		return "api/portList";
	}

	/**
	 * 根据接口名称查询接口信息.
	 * @author zhangcq
	 * @date Jan 13, 2017
	 * @comment 
	 * @param request
	 * @param response
	 * @param module
	 * @return
	 */
	@RequestMapping("/api/{portName}/detail.do")
	public String showThePortDetail( HttpServletRequest request,
			HttpServletResponse response,
			@PathVariable String portName )
	{
//		String portStr = loadPackageFile(portPath,port+".port");
//		String detailPath = "a/autocode/app/port/backup/";
		if ( StringUtil.isEmpty(detailPath) )
		{
			return "jsp/error";
		}
		
		String refUrl = request.getParameter("refUrl");
		XLog.log("refUrl=%s", refUrl);
		XLog.log("detailPath=%s", detailPath);
		
		JAPIParser apiParse = new JAPIParser("classpath:"+detailPath+portName+".port");
		try {
			apiParse.doParse();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		XLog.log("AFTER-PARSE:%s-%s", apiParse.config.getBeanName(),apiParse.config.getBeanDesc());
		
		request.setAttribute("detaiInfo",apiParse.config);
		request.setAttribute("refUrl", refUrl);
		return "api/portDetail";
	}

	//从包下面加载文件.
	private String loadPackageFile( String packageName, String fileName )
	{
		packageName = packageName.replace(".", File.separator)+File.separator;
		String filePath = packageName+fileName;
		
		//json config.
		byte[] data = new byte[1024];
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		BufferedInputStream is=null;
		try {
			int len = 0;
			is = new BufferedInputStream(getClass().getClassLoader().getResourceAsStream(filePath));
			while ( true )
			{
				len = is.read(data);
				if( len  == -1 )
					break;
				
				stream.write(data, 0, len);
			}
			
			is.close();	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String retStr = null;
		try {
			retStr = new String( stream.toByteArray(),"utf-8");
			return retStr;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return retStr;
	}
}
